package com.yonyou.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yonyou.exception.ErrorMessageException;
import com.yonyou.model.*;
import com.yonyou.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.Arrays;
import java.util.stream.Collectors;



/**
 * @author wangchu
 * @date 2025-05-01 23:21
 */
@Slf4j
@RestController
@RequestMapping("/api")
public class OerCzzfdController {

    @Autowired
    private OerSecCzzfdService czzfdService;
    @Autowired
    private OerSecCzzbService czzbService;
    @Autowired
    private OerSecCzzbGkService czzbGkService;
    @Autowired
    private OerSecCzzbSyService czzbSyService;

    @GetMapping("/sqdcx/page.html")
    public ModelAndView sqdcx(String key) {
        return new ModelAndView("main/sqdcx")
                .addObject("key", key);
    }

    @GetMapping("/zbcx/page.html")
    public ModelAndView zbcx(String key) {
        return new ModelAndView("main/zbcx")
                .addObject("key", key);
    }

    @GetMapping("/zbyeb/page.html")
    public ModelAndView zbyeb(String key) {
        if ("gkjzzfzbyeb".equals(key)) {
            return new ModelAndView("main/gkjzzfzbyeb");
        } else if ("syzjzbyeb".equals(key)) {
            return new ModelAndView("main/syzjzbyeb");
        } else {
            throw new ErrorMessageException("key无效！");
        }
    }

    @GetMapping("/detailPage.html")
    public ModelAndView detailPage(String id) {
        return new ModelAndView("main/detail")
                .addObject("id", id);
    }

    /**
     * 查询待支付明细
     * @return
     */
    @PostMapping("/searchPayInfos")
    public ResultEntity<?> searchPayInfos() {
        List<OerSecCzzfd> payInfos = czzfdService.searchPayInfos();
        for (OerSecCzzfd payInfo : payInfos) {
            payInfo.setGwksksj(payInfo.getCrerdate().substring(0, 4) + "-" +  payInfo.getCrerdate().substring(4, 6) + "-" +  payInfo.getCrerdate().substring(6));
        }
        return ResultEntity.success(payInfos);
    }

    /**
     * 匹配财政支付指标
     * @param request
     * @return
     */
    @PostMapping("/indexMatch")
    public ResultEntity<?> indexMatch(HttpServletRequest request) throws Exception {
        // 获取Body参数
        String postParam = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        if (JSONUtil.isJsonObj(postParam)) {
            // 将参数转换为JSON对象
            JSONObject po = JSONUtil.parseObj(postParam);
            // 获取支付ID
            if (!po.containsKey("zfid")) {
                return ResultEntity.fail("zfid缺失！");
            }
            String zfid = po.getStr("zfid");
            // 获取指标列表
            if (!po.containsKey("indexArray")) {
                return ResultEntity.fail("indexArray缺失！");
            }
            if (!JSONUtil.isJsonArray(String.valueOf(po.get("indexArray")))) {
                return ResultEntity.fail("indexArray结构校验失败！");
            }
            JSONArray indexArray = po.getJSONArray("indexArray");
            JSONArray secArray = new JSONArray();
            // 列表必填项校验
            int indes = 1;
            for (Object o : indexArray) {
                JSONObject jo = JSONUtil.parseObj(o);
                if (!jo.containsKey("可用余额")) {
                    return ResultEntity.fail("第" + indes + "个指标中，【可用余额】不能为空！");
                }
                if (!NumberUtil.isNumber(jo.getStr("可用余额"))) {
                    return ResultEntity.fail("第" + indes + "个指标中，【可用余额】应为数字！");
                }
                if (jo.getDouble("可用余额") <= 0) {
                    return ResultEntity.fail("第" + indes + "个指标中，【可用余额】必须大于0！");
                }
                if (!jo.containsKey("指标摘要")) {
                    return ResultEntity.fail("第" + indes + "个指标中，【指标摘要】不能为空！");
                }
                if (!jo.containsKey("部门经济分类")) {
                    return ResultEntity.fail("第" + indes + "个指标中，【部门经济分类】不能为空！");
                }
                if (!jo.containsKey("政府经济分类")) {
                    return ResultEntity.fail("第" + indes + "个指标中，【政府经济分类】不能为空！");
                }
                if (!jo.containsKey("支出功能分类")) {
                    return ResultEntity.fail("第" + indes + "个指标中，【支出功能分类】不能为空！");
                }
                if (!jo.containsKey("资金性质")) {
                    return ResultEntity.fail("第" + indes + "个指标中，【资金性质】不能为空！");
                }
                if (!jo.containsKey("项目")) {
                    return ResultEntity.fail("第" + indes + "个指标中，【项目】不能为空！");
                }
                if (!jo.containsKey("是否包含政府采购")) {
                    return ResultEntity.fail("第" + indes + "个指标中，【是否包含政府采购】不能为空！");
                }
                if (!jo.containsKey("指标类型")) {
                    return ResultEntity.fail("第" + indes + "个指标中，【指标类型】不能为空！");
                }
                if (!jo.containsKey("指标文号")) {
                    return ResultEntity.fail("第" + indes + "个指标中，【指标文号】不能为空！");
                }
                indes ++;

                JSONObject nj = new JSONObject()
                        .set("序号", jo.get("序号"))
                        .set("原始金额", jo.get("原始金额"))
                        .set("可用余额", jo.get("可用余额"))
                        .set("指标摘要", jo.get("指标摘要"))
                        .set("部门经济分类", jo.get("部门经济分类"))
                        .set("政府经济分类", jo.get("政府经济分类"))
                        .set("支出功能分类", jo.get("支出功能分类"))
                        .set("资金性质", jo.get("资金性质"))
                        .set("项目", jo.get("项目"))
                        .set("是否包含政府采购", jo.get("是否包含政府采购"))
                        .set("指标类型", jo.get("指标类型"))
                        .set("指标文号", jo.get("指标文号"));
                secArray.add(nj);
            }

            // 匹配指标
            List<JSONObject> indexes = czzfdService.matchIndex(zfid, secArray);
            czzfdService.processAndSaveIndexMatch(zfid, new JSONArray(indexes));
            return ResultEntity.success(indexes);
        } else {
            return ResultEntity.fail("参数校验错误！");
        }
    }

    /**
     * 制单失败邮件通知接口
     * @param entity
     * @return
     */
    @PostMapping("/failMessage")
    public ResultEntity<?> failMessage(@RequestBody RequestEntity entity) {
        czzfdService.failMessage(entity);
        return ResultEntity.success();
    }

    /**
     * 制单成功标记接口
     * @param entity
     * @return
     */
    @PostMapping("/successNote")
    public ResultEntity<?> successNote(@RequestBody RequestEntity entity) {
        czzfdService.successNote(entity);
        return ResultEntity.success();
    }
    /**
     * 构建支付单查询条件
     * @param entity 查询条件实体
     * @return LambdaQueryWrapper<OerSecCzzfd>
     */
    private LambdaQueryWrapper<OerSecCzzfd> buildCzzfdQueryWrapper(OerSecCzzfd entity) {
        LambdaQueryWrapper<OerSecCzzfd> wrapper = new LambdaQueryWrapper<OerSecCzzfd>()
                .orderByDesc(OerSecCzzfd::getZdsj);

        // 支付状态
        if (Objects.nonNull(entity.getZfzt())) {
            wrapper.eq(OerSecCzzfd::getZfzt, entity.getZfzt());
        }
        // 制单日期
        if (StrUtil.isNotBlank(entity.getZdsj())) {
            String[] zdsj = entity.getZdsj().split(" - ");
            String s = zdsj[0];
            String e = zdsj[1];
            wrapper.ge(OerSecCzzfd::getZdsj, s)
                    .le(OerSecCzzfd::getZdsj, e);
        }
        // 支付单据类型
        if (StrUtil.isNotBlank(entity.getZfdjlx())) {
            String[] zfdjlxs = entity.getZfdjlx().split(",");
            if (zfdjlxs.length == 1) {
                wrapper.eq(OerSecCzzfd::getZfdjlx, entity.getZfdjlx());
            } else {
                wrapper.in(OerSecCzzfd::getZfdjlx, Arrays.asList(zfdjlxs));
            }
        }
        // 单据类型名称
        if (StrUtil.isNotBlank(entity.getDjlxmc())) {
            wrapper.like(OerSecCzzfd::getDjlxmc, entity.getDjlxmc());
        }
        // 单据编号
        if (StrUtil.isNotBlank(entity.getDjbh())) {
            wrapper.like(OerSecCzzfd::getDjbh, entity.getDjbh());
        }
        // 支付金额范围查询
        if (Objects.nonNull(entity.getZfjeMin()) || Objects.nonNull(entity.getZfjeMax())) {
            if (Objects.nonNull(entity.getZfjeMin())) {
                wrapper.ge(OerSecCzzfd::getZfje, entity.getZfjeMin());
            }
            if (Objects.nonNull(entity.getZfjeMax())) {
                wrapper.le(OerSecCzzfd::getZfje, entity.getZfjeMax());
            }
        }
        // 摘要
        if (StrUtil.isNotBlank(entity.getZy())) {
            wrapper.and(
                    w -> w.like(OerSecCzzfd::getZy, "%" + entity.getZy() + "%")
                            .or()
                            .like(OerSecCzzfd::getNrzy, "%" + entity.getZy() + "%")
                            .or()
                            .like(OerSecCzzfd::getZbzy, "%" + entity.getZy() + "%")
                            .or()
                            .like(OerSecCzzfd::getDjzbzy, "%" + entity.getZy() + "%")
            );
        }
        // 是否存疑
        if (Objects.nonNull(entity.getDoubt())) {
            wrapper.eq(OerSecCzzfd::getDoubt, entity.getDoubt());
        }
        // 收款人信息
        if (StrUtil.isNotBlank(entity.getSkr())) {
            wrapper.and(
                    w -> w.like(OerSecCzzfd::getSkr , "%" + entity.getSkr() + "%")
                            .or()
                            .like(OerSecCzzfd::getKhyh, "%" + entity.getSkr() + "%")
                            .or()
                            .like(OerSecCzzfd::getYhzh, "%" + entity.getSkr() + "%")
                            .or()
                            .like(OerSecCzzfd::getGwkh, "%" + entity.getSkr() + "%")
            );
        }
        // 审核人
        if (StrUtil.isNotBlank(entity.getAuditor())) {
            wrapper.like(OerSecCzzfd::getAuditor, entity.getAuditor());
        }

        // 模糊条件
        if (StrUtil.isNotBlank(entity.getExtra())) {
            wrapper.and(
                    w -> w.like(OerSecCzzfd::getXmdm, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getXmmc, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getYsxmdm, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getYsxmmc, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getZjxzdm, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getZjxzmc, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getWhdm, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getWhmc, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getZfcgfs, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getZfcghtbh, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getZfzbzy, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getZfbmjjfl, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getZfzfjjfl, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getZfzcgnfl, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getZfzjxz, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getZfzblx, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getZfxm, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getZfzbwh, "%" + entity.getExtra() + "%")
                            .or()
                            .like(OerSecCzzfd::getZfztbzxx, "%" + entity.getExtra() + "%")
            );
        }
        return wrapper;
    }

    /**
     * 列表查询
     */
    @RequestMapping("/pageList")
    public LayuiPageModel<OerSecCzzfd> searchPageList(LayuiPageModel<OerSecCzzfd> layPageModel, OerSecCzzfd entity) {
        LambdaQueryWrapper<OerSecCzzfd> wrapper = buildCzzfdQueryWrapper(entity);

        Page<OerSecCzzfd> list = (Page<OerSecCzzfd>) czzfdService.page(
                new Page<>(layPageModel.getPage(), layPageModel.getLimit()),
                wrapper
        );

        // 计算合计金额
        LambdaQueryWrapper<OerSecCzzfd> totalWrapper = buildCzzfdQueryWrapper(entity);
        List<OerSecCzzfd> allRecords = czzfdService.list(totalWrapper);
        double totalAmount = allRecords.stream()
                .mapToDouble(OerSecCzzfd::getZfje)
                .sum();

        layPageModel.setCount(list.getTotal())
                .setData(list.getRecords())
                .setOther("totalZfje", totalAmount); // 添加合计金额到返回结果
        return layPageModel;
    }


    /**
     * 列表查询
     */
    @RequestMapping("/zbpageList")
    public LayuiPageModel<OerSecCzzb> searchZbPageList(LayuiPageModel<OerSecCzzb> layPageModel, OerSecCzzb entity) {
        LambdaQueryWrapper<OerSecCzzb> wrapper = new LambdaQueryWrapper<OerSecCzzb>()
                .orderByDesc(OerSecCzzb::getId);
        // 指标模块
        if (Objects.nonNull(entity.getZbmk())) {
            wrapper.eq(OerSecCzzb::getZbmk, entity.getZbmk());
        }
        // 指标摘要
        if (StrUtil.isNotBlank(entity.getZbzy())) {
            wrapper.like(OerSecCzzb::getZbzy, entity.getZbzy());
        }
        // 部门经济分类
        if (StrUtil.isNotBlank(entity.getBmjjfl())) {
            wrapper.like(OerSecCzzb::getBmjjfl, entity.getBmjjfl());
        }
        // 政府经济分类
        if (StrUtil.isNotBlank(entity.getZfjjfl())) {
            wrapper.like(OerSecCzzb::getZfjjfl, entity.getZfjjfl());
        }
        // 支出功能分类
        if (StrUtil.isNotBlank(entity.getZcgnfl())) {
            wrapper.like(OerSecCzzb::getZcgnfl, entity.getZcgnfl());
        }
        // 资金性质
        if (StrUtil.isNotBlank(entity.getZjxz())) {
            wrapper.like(OerSecCzzb::getZjxz, entity.getZjxz());
        }
        // 项目
        if (StrUtil.isNotBlank(entity.getXm())) {
            wrapper.like(OerSecCzzb::getXm, entity.getXm());
        }
        // 指标文号
        if (StrUtil.isNotBlank(entity.getZbwh())) {
            wrapper.like(OerSecCzzb::getZbwh, entity.getZbwh());
        }
        Page<OerSecCzzb> list = (Page<OerSecCzzb>) czzbService.page(
                new Page<>(layPageModel.getPage(), layPageModel.getLimit()),
                wrapper
        );
        layPageModel.setCount(list.getTotal())
                .setData(list.getRecords());
        return layPageModel;
    }

    /**
     * 列表查询
     */
    @RequestMapping("/gkjzzfpageList")
    public LayuiPageModel<OerSecCzzbGk> gkjzzfpageList(LayuiPageModel<OerSecCzzbGk> layPageModel, OerSecCzzbGk entity) {
        LambdaQueryWrapper<OerSecCzzbGk> wrapper = new LambdaQueryWrapper<OerSecCzzbGk>()
                .orderByDesc(OerSecCzzbGk::getId);
        // 指标模块
        if (Objects.nonNull(entity.getZy())) {
            wrapper.like(OerSecCzzbGk::getZy, entity.getZy());
        }
        // 指标摘要
        if (StrUtil.isNotBlank(entity.getXmkxmlb())) {
            wrapper.like(OerSecCzzbGk::getXmkxmlb, entity.getXmkxmlb());
        }
        // 部门经济分类
        if (StrUtil.isNotBlank(entity.getCzxmbm())) {
            wrapper.like(OerSecCzzbGk::getCzxmbm, entity.getCzxmbm());
        }
        // 政府经济分类
        if (StrUtil.isNotBlank(entity.getCzxmmc())) {
            wrapper.like(OerSecCzzbGk::getCzxmmc, entity.getCzxmmc());
        }
        // 支出功能分类
        if (StrUtil.isNotBlank(entity.getWh())) {
            wrapper.like(OerSecCzzbGk::getWh, entity.getWh());
        }
        // 资金性质
        if (StrUtil.isNotBlank(entity.getCzzjxz())) {
            wrapper.like(OerSecCzzbGk::getCzzjxz, entity.getCzzjxz());
        }
        // 项目
        if (StrUtil.isNotBlank(entity.getCzgnkm())) {
            wrapper.like(OerSecCzzbGk::getCzgnkm, entity.getCzgnkm());
        }
        // 指标文号
        if (StrUtil.isNotBlank(entity.getCzzfjjkm())) {
            wrapper.like(OerSecCzzbGk::getCzzfjjkm, entity.getCzzfjjkm());
        }
        // 指标文号
        if (StrUtil.isNotBlank(entity.getCzbmjjkm())) {
            wrapper.like(OerSecCzzbGk::getCzbmjjkm, entity.getCzbmjjkm());
        }
        Page<OerSecCzzbGk> list = (Page<OerSecCzzbGk>) czzbGkService.page(
                new Page<>(layPageModel.getPage(), layPageModel.getLimit()),
                wrapper
        );
        layPageModel.setCount(list.getTotal())
                .setData(list.getRecords());
        return layPageModel;
    }

    /**
     * 列表查询
     */
    @RequestMapping("/syzjpageList")
    public LayuiPageModel<OerSecCzzbSy> syzjpageList(LayuiPageModel<OerSecCzzbSy> layPageModel, OerSecCzzbSy entity) {
        LambdaQueryWrapper<OerSecCzzbSy> wrapper = new LambdaQueryWrapper<OerSecCzzbSy>()
                .orderByDesc(OerSecCzzbSy::getId);
        // 指标模块
        if (Objects.nonNull(entity.getYh())) {
            wrapper.like(OerSecCzzbSy::getYh, entity.getYh());
        }
        // 指标摘要
        if (StrUtil.isNotBlank(entity.getXmlbmc())) {
            wrapper.like(OerSecCzzbSy::getXmlbmc, entity.getXmlbmc());
        }
        // 部门经济分类
        if (StrUtil.isNotBlank(entity.getZbwh())) {
            wrapper.like(OerSecCzzbSy::getZbwh, entity.getZbwh());
        }
        // 政府经济分类
        if (StrUtil.isNotBlank(entity.getZjlymc())) {
            wrapper.like(OerSecCzzbSy::getZjlymc, entity.getZjlymc());
        }
        // 支出功能分类
        if (StrUtil.isNotBlank(entity.getCzgnkm())) {
            wrapper.like(OerSecCzzbSy::getCzgnkm, entity.getCzgnkm());
        }
        // 资金性质
        if (StrUtil.isNotBlank(entity.getCzzfjjkm())) {
            wrapper.like(OerSecCzzbSy::getCzzfjjkm, entity.getCzzfjjkm());
        }
        // 项目
        if (StrUtil.isNotBlank(entity.getCzbmjjkm())) {
            wrapper.like(OerSecCzzbSy::getCzbmjjkm, entity.getCzbmjjkm());
        }
        Page<OerSecCzzbSy> list = (Page<OerSecCzzbSy>) czzbSyService.page(
                new Page<>(layPageModel.getPage(), layPageModel.getLimit()),
                wrapper
        );
        layPageModel.setCount(list.getTotal())
                .setData(list.getRecords());
        return layPageModel;
    }

    /**
     * 查询明细
     */
    @GetMapping("/getDetail")
    public ResultEntity<?> searchDetail(String id) {
        if (StrUtil.isBlank(id)) {
            throw new ErrorMessageException("ID不能为空！");
        }
        OerSecCzzfd czzfd = czzfdService.getById(id);
        if (Objects.isNull(czzfd)) {
            throw new ErrorMessageException("ID无效！");
        }
        return ResultEntity.success(czzfd);
    }

    /**
     * 标记存疑
     */
    @PostMapping("/markDoubt")
    public ResultEntity<?> markDoubt(String id, String doubtzy) {
        if (StrUtil.isBlank(id)) {
            throw new ErrorMessageException("ID不能为空！");
        }
        OerSecCzzfd czzfd = czzfdService.getById(id);
        if (Objects.isNull(czzfd)) {
            throw new ErrorMessageException("ID无效！");
        }
        czzfd.setDoubt(1)
                .setDoubtzy(doubtzy);
        czzfdService.updateById(czzfd);
        return ResultEntity.success("操作成功！");
    }

    /**
     * 取消存疑
     */
    @PostMapping("/cancelDoubt")
    public ResultEntity<?> cancelDoubt(String id) {
        if (StrUtil.isBlank(id)) {
            throw new ErrorMessageException("ID不能为空！");
        }
        OerSecCzzfd czzfd = czzfdService.getById(id);
        if (Objects.isNull(czzfd)) {
            throw new ErrorMessageException("ID无效！");
        }
        czzfd.setDoubt(0)
                .setDoubtzy("");
        czzfdService.updateById(czzfd);
        return ResultEntity.success("操作成功！");
    }

    /**
     * 获取首页统计数据
     * @return
     */
    @GetMapping("/getDashboardData")
    public ResultEntity<?> getDashboardData() {
        JSONObject data = czzfdService.getDashboardData();
        return ResultEntity.success(data);
    }

    /**
     * 导出全部数据
     * @param response
     * @param entity
     * @throws Exception
     */
    @GetMapping("/exportAll")
    public void exportAll(HttpServletResponse response, OerSecCzzfd entity) throws Exception {
        try {
            // 设置响应头
            String fileName = java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + " RPA支付数据.xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));

            // 使用通用方法构建查询条件
            LambdaQueryWrapper<OerSecCzzfd> wrapper = buildCzzfdQueryWrapper(entity);

            // 查询所有数据
            List<OerSecCzzfd> list = czzfdService.list(wrapper);

            // 使用 Apache POI 创建 Excel
            org.apache.poi.xssf.usermodel.XSSFWorkbook workbook = new org.apache.poi.xssf.usermodel.XSSFWorkbook();
            org.apache.poi.ss.usermodel.Sheet sheet = workbook.createSheet("RPA支付数据");

            // 创建表头
            org.apache.poi.ss.usermodel.Row headerRow = sheet.createRow(0);
            String[] headers = {"序号", "支付单类型", "支付单状态", "支付金额", "制单时间", "原始单据编号", "收款人",
                               "银行账号", "U8单据类型", "U8项目", "U8指标", "U8预算项目", "U8资金性质",
                               "U8指标文号", "是否政府采购", "财政部门经济分类", "财政政府经济分类",
                               "财政支出功能分类", "财政资金性质", "财政指标类型", "财政预算项目",
                               "财政指标文号", "制单状态备注", "是否存疑", "存疑摘要", "审核人"};

            for (int i = 0; i < headers.length; i++) {
                org.apache.poi.ss.usermodel.Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 填充数据
            // 填充数据（按照前端显示格式化）
            for (int i = 0; i < list.size(); i++) {
                OerSecCzzfd item = list.get(i);
                org.apache.poi.ss.usermodel.Row row = sheet.createRow(i + 1);

                row.createCell(0).setCellValue(i + 1);
                row.createCell(1).setCellValue(item.getZfdjlx() != null ? item.getZfdjlx() : "");
                row.createCell(2).setCellValue(getZfztText(item.getZfzt()));
                row.createCell(3).setCellValue(item.getZfje() != null ? formatCurrency(item.getZfje()) : "0.00");
                row.createCell(4).setCellValue(item.getZdsj() != null ? item.getZdsj() : "");
                row.createCell(5).setCellValue(item.getDjbh() != null ? item.getDjbh() : "");
                row.createCell(6).setCellValue(item.getSkr() != null ? item.getSkr() : "");
                row.createCell(7).setCellValue(formatBankAccount(item));
                row.createCell(8).setCellValue(item.getDjlxmc() != null ? item.getDjlxmc() : "");
                row.createCell(9).setCellValue(formatCombinedField(item.getXmdm(), item.getXmmc()));
                row.createCell(10).setCellValue(formatCombinedField(String.valueOf(item.getZbid()), item.getZbzy()));
                row.createCell(11).setCellValue(formatCombinedField(item.getYsxmdm(), item.getYsxmmc()));
                row.createCell(12).setCellValue(formatCombinedField(item.getZjxzdm(), item.getZjxzmc()));
                row.createCell(13).setCellValue(formatCombinedField(item.getWhdm(), item.getWhmc()));
                row.createCell(14).setCellValue(getSfzfcgText(item.getSfzfcg()));

                row.createCell(15).setCellValue(item.getZfbmjjfl() != null ? item.getZfbmjjfl() : "");
                row.createCell(16).setCellValue(item.getZfzfjjfl() != null ? item.getZfzfjjfl() : "");
                row.createCell(17).setCellValue(item.getZfzcgnfl() != null ? item.getZfzcgnfl() : "");
                row.createCell(18).setCellValue(item.getZfzjxz() != null ? item.getZfzjxz() : "");
                row.createCell(19).setCellValue(item.getZfzblx() != null ? item.getZfzblx() : "");
                row.createCell(20).setCellValue(item.getZfxm() != null ? item.getZfxm() : "");
                row.createCell(21).setCellValue(item.getZfzbwh() != null ? item.getZfzbwh() : "");
                row.createCell(22).setCellValue(item.getZfztbzxx() != null ? item.getZfztbzxx() : "");
                row.createCell(23).setCellValue(getDoubtText(item.getDoubt()));
                row.createCell(24).setCellValue(item.getDoubtzy() != null ? item.getDoubtzy() : "");
                row.createCell(25).setCellValue(item.getAuditor() != null ? item.getAuditor() : "");
            }


            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 写入响应流
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            log.error("导出Excel失败", e);
            throw new ErrorMessageException("导出失败: " + e.getMessage());
        }
    }
    // 获取支付状态文本
    private String getZfztText(Integer zfzt) {
        if (zfzt == null) {
            return "";
        }
        if (zfzt == 0) {
            return "待支付";
        } else if (zfzt == 1) {
            return "制单成功";
        } else if (zfzt == 2) {
            return "制单失败";
        }
        return "";
    }
    // 格式化金额（类似前端的 zfjeTemplate）
    private String formatCurrency(Double amount) {
        if (amount == null) {
            return "0.00";
        }
        java.text.DecimalFormat df = new java.text.DecimalFormat("#,##0.00");
        return df.format(amount);
    }

    // 获取是否政府采购文本（类似前端的 sfzfcgTemplate）
    private String getSfzfcgText(Integer sfzfcg) {
        if (sfzfcg == 1) {
            return "是";
        } else {
            return "否";
        }
    }

    // 获取是否存疑文本（类似前端的 doubtTemplate）
    private String getDoubtText(Integer doubt) {
        if (doubt != null && doubt == 1) {
            return "是";
        } else {
            return "否";
        }
    }

    // 格式化银行账号/公务卡号（类似前端的 yhzhTemplate）
    private String formatBankAccount(OerSecCzzfd item) {
        if ("公务卡申请".equals(item.getZfdjlx())) {
            return item.getGwkh() != null ? item.getGwkh() : (item.getYhzh() != null ? item.getYhzh() : "");
        } else {
            return item.getYhzh() != null ? item.getYhzh() : (item.getGwkh() != null ? item.getGwkh() : "");
        }
    }

    // 格式化组合字段（类似前端的 xmdmTemplate 等）
    private String formatCombinedField(String code, String name) {
        if (code == null && name == null) {
            return "";
        }
        return (code != null ? code : "") + " " + (name != null ? name : "");
    }

}